package org.atguigu.gmall.realtime.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.atguigu.gmall.realtime.common.Constant;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;


/**
 * Project:gmallRealTime
 * Package:org.atguigu.gmall.realtime.util
 * Author: ZengHaiFeng
 * CreateTime:2023/5/4 21:10:05
 * Description: Todo
 * Version：1.0
 */
public class DimUtil {
    public static JSONObject readDim(Jedis redisClient, Connection conn, String table, String id) {
        JSONObject dim = readDimFromRedis(redisClient,table,id);
        if (dim == null){
            dim = readDimFromPhoenix(conn,table,id);
            writeToRedis(redisClient,table,id,dim);
            System.out.println("从 数据库 读取到维度: " + table + " " + id);
        }else {
            System.out.println("从 缓存 读取到维度: " + table + " " + id);
        }
        return dim;
    }

    private static void writeToRedis(Jedis redisClient, String table, String id, JSONObject dim) {
        String key = getKey(table, id);
        redisClient.setex(key, Constant.TWO_DAYS,dim.toJSONString());
    }

    private static JSONObject readDimFromPhoenix(Connection conn, String table, String id) {
        String sql = "select * from " + table + " where id = ? ";
        List<JSONObject> jsonObjects = JdbcUtil.queryList(conn, sql, new Object[]{id}, JSONObject.class);
        if (jsonObjects.size() == 0){
            throw new RuntimeException("没有查询到维度数据:" + table + "  " + id + ", 请检测 id 是否正确和维度表中是否有数据");
        }
        return jsonObjects.get(0);
    }

    private static JSONObject readDimFromRedis(Jedis redisClient, String table, String id) {
        String key = getKey(table,id);
        String s = redisClient.get(key);
        if (s != null){
            return JSON.parseObject(s);
        }
        return null;
    }

    private static String getKey(String table, String id) {
        return table + ":" + id;
    }
}
